<template>
  <auth-component title="注册">
    <el-form
      ref="ruleFormRef"
      style="max-width: 400px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="用户名" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>
      <el-form-item label="二次密码" prop="password2">
        <el-input v-model="ruleForm.password2" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          注册
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </auth-component>
</template>

<script setup lang="ts">

import AuthComponent from '@/components/AuthComponent.vue'
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { register } from '@/apis/user'
import { useRouter } from 'vue-router'

const router = useRouter()

interface RuleForm {
  name: string
  password: string
  password2: string
}

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  name: '',
  password: '',
  password2: ''
})

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value !== ruleForm.password) {
    callback(new Error('两次密码不一致'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 15, message: '长度基于5-15之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 20, message: '长度基于8-20之间', trigger: 'blur' }
  ],
  password2: [
    { required: true, message: '请输入二次密码', trigger: 'blur' },
    { min: 8, max: 20, message: '长度基于8-20之间', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate()
  const { data } = await register({
    username: ruleForm.name,
    password: ruleForm.password,
    password2: ruleForm.password2
  })
  if (data.code === 0) {
    await router.push('/login')
  } else {
    resetForm(formEl)
  }
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped>

</style>